package com.uchedao.seller.ui.car.publish.condition;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.seller.R;
import com.uchedao.seller.db.DbHelper;
import com.uchedao.seller.inf.IOnResultBack;
import com.uchedao.seller.module.Condition;
import com.uchedao.seller.module.Draft;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.module.ResultIntArrayPics;
import com.uchedao.seller.ui.car.publish.ImagePagerActivity;
import com.uchedao.seller.ui.car.adapter.PaintSurfaceAdapter;
import com.uchedao.seller.ui.car.adapter.PaintSurfaceAdapter.PaintSurfaceAdapterListener;
import com.uchedao.seller.util.Util;
import com.uchedao.seller.widget.loadstate.UCheDaoRelativeLayout;
import com.uchedao.seller.widget.stickylistheaders.StickyListHeadersListView;

import java.io.File;
import java.util.ArrayList;

/**
 * 漆面检测
 */
public class ConditionPaintSurfaceView extends UCheDaoRelativeLayout implements PaintSurfaceAdapterListener,IOnResultBack {

    public static final int FROM_CAMERA = 301;// 拍照获取

    public static final int FROM_PICTURE = 302;// 从图库获取

    public static final int FROM_PIC_VIEWPAGER = 303;// 从图片浏览返回

    private ResultIntArrayPics tmpItem;

    private AlertDialog pickerDialog;// 图片选取对话框

    private String tmpPath;// 临时图片路径

    //    private Condition condition = GlobalInfo.draft.condition.clone();
    private Condition condition;
//    private ResultIntArrayPics[] paint_surface;

    private PaintSurfaceAdapter paintSurfaceAdapter;

    public ConditionPaintSurfaceView(Context context) {
        super(context);
    }

    public ConditionPaintSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ConditionPaintSurfaceView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean save() {

        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(condition));

        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);

        // 若VIN值为空
        if (TextUtils.isEmpty(condition.config_info.vin))
            condition.config_info.vin = GlobalInfo.draft.car_vin;

            // 如果VIN值有更改
        else if (!condition.config_info.vin.equals(GlobalInfo.draft.car_vin)) {
            values.put(DbHelper.KEY_DRAFT_CAR_VIN, condition.config_info.vin);
        }

        // int status = GlobalInfo.draft.status[Draft.TYPE_CONDITION];
        // // 若原先状态为未完成，且数据已变动，则状态改变为已完成
        // if (GlobalInfo.draft.status[Draft.TYPE_CONDITION] !=
        // Draft.STATUE_FINISH) {
        // values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, Draft.STATUE_FINISH);
        // status = Draft.STATUE_FINISH;
        // }

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.tempOwner, values)) {
            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            L.i(toJson(GlobalInfo.draft.condition));

            return noEmptyTerm();
        }

        return false;
    }

    /**
     * 没有空项
     */
    public boolean noEmptyTerm() {
        for (int i = 0; i < condition.paint_surface.length; i++) {
            if (condition.paint_surface[i].result.size() <= 0)
                return false;
        }
        return true;
    }

    /**
     * 一键全部正常
     */
    public void checkAllOk() {
        for (int i = 0; i < condition.paint_surface.length; i++) {
            if (condition.paint_surface[i].result.size() <= 0)
                condition.paint_surface[i].result.add(0);
        }
        paintSurfaceAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean dataChanged() {

//        L.i(toJson(condition));
//        L.i(toJson(GlobalInfo.draft.condition));
        return !toJson(condition).equals(toJson(GlobalInfo.draft.condition));
//        return false;
    }

    @Override
    public void initView() {

        LayoutInflater.from(mContext).inflate(R.layout.view_detection, this);
        StickyListHeadersListView stickListHeadersListView = (StickyListHeadersListView) findViewById(R.id.detection_listView);
        paintSurfaceAdapter = new PaintSurfaceAdapter(mContext, getPaintSurfaceData(), this);
        stickListHeadersListView.setAdapter(paintSurfaceAdapter);

    }

    @Override
    public void initDataAfterView() {

    }

    @Override
    public void initDataBeforView() {
//        if (GlobalInfo.draft == null) {
//            GlobalInfo.draft = new Draft();
//        }
        condition = GlobalInfo.draft.condition.clone();

    }

    @Override
    public void initListener() {

    }

    @Override
    public void onPhotoAdd(ResultIntArrayPics item) {
        tmpItem = item;
        L.i(toJson(item));
        showPickerDialog();
    }

    @Override
    public void onPhotoEdit(ResultIntArrayPics item) {
        tmpItem = item;
        // 图片浏览软件
        Intent intent = new Intent(mContext, ImagePagerActivity.class);
        intent.putExtra("title", item.name);
        intent.putStringArrayListExtra("pic_path_list", item.pic_path_list);
        ((Activity) mContext).startActivityForResult(intent, FROM_PIC_VIEWPAGER);
    }

    /**
     * 漆面检测数据
     *
     * @return
     */
    private ResultIntArrayPics[] getPaintSurfaceData() {

        //获取数据暂时有问题，
//        GlobalInfo.draft.condition.clone();
        if (condition == null) {
            condition = new Condition();
        }
//        ResultIntArrayPics[] paint_surface = new ResultIntArrayPics[17];

        String header = GlobalInfo.resources.getString(R.string.check_part);

        String[] texts = GlobalInfo.resources.getStringArray(R.array.paint_car_entries);
        for (int i = 0; i < texts.length; i++) {
            if (condition.paint_surface[i] == null)
                condition.paint_surface[i] = new ResultIntArrayPics();
            condition.paint_surface[i].header = header;
            condition.paint_surface[i].name = texts[i];
            if (condition.paint_surface[i].result == null) {
                condition.paint_surface[i].result = new ArrayList<Integer>();
            }
//            if (condition.paint_surface[i].result.size() == 0)
//                condition.paint_surface[i].result.add(0);
        }
        return condition.paint_surface;
    }

    /**
     * 显示图片选取对话框
     */
    public void showPickerDialog() {
        if (pickerDialog == null) {
            CharSequence[] items = {"拍照", "从图片库选择"};
            pickerDialog = new AlertDialog.Builder(mContext).setTitle("选择")
                    .setItems(items, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
                                tmpPath = file.getAbsolutePath();
                                Uri uri = Uri.fromFile(file);
                                i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                ((Activity) mContext).startActivityForResult(i, FROM_CAMERA);

                            } else {

                                Intent intent = new Intent();
                                /* 开启Pictures画面Type设定为image */
                                intent.setType("image/*");
                                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                                // intent.setAction(Intent.ACTION_GET_CONTENT);
                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                                } else {
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                }
                                /* 取得相片后返回本画面 */
                                ((Activity) mContext).startActivityForResult(intent, FROM_PICTURE);
                            }
                        }
                    }).create();
        }
        pickerDialog.show();

    }

    public void onActivityResultView(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case FROM_CAMERA:// 相机
                    tmpItem.pic_path_list.add(tmpPath);
                    break;

                case FROM_PICTURE:// 图库
                    Uri uri = data.getData();
                    tmpPath = Util.getPath(mContext, uri);
                    L.i("uri = " + uri.toString() + " path=" + tmpPath);
                    tmpItem.pic_path_list.add(tmpPath);
                    break;

                case FROM_PIC_VIEWPAGER:// 图片浏览
                    tmpItem.pic_path_list = data.getStringArrayListExtra("pic_path_list");
                    break;

            }

            paintSurfaceAdapter.notifyDataSetChanged();

        }

    }
}
